<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@page import="java.util.Calendar"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.text.DateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>
<%@ page import = "java.io.*" %>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Login</title>
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" /> 
	<link rel="stylesheet" type="text/css" href="css/login.css">
	<!-- test -->
	<style type="text/css">
		#main-content-act {
			background:rgba(0,0,0,0.2);
			padding-left: 50px;
			padding-top: 30px;
			padding-right: 10px;
		}
	</style>	
</head>
<body>

<%
	// check session
	HttpSession htp_session = request.getSession();
	
	if (htp_session.getAttribute("sUser") != null) {
		
		if("admin".equals(htp_session.getAttribute("sUser"))) {
			request.getRequestDispatcher("/admin_home.jsp").forward(request,
			        response);
		}
		else {
			request.getRequestDispatcher("/system_select.jsp").forward(request,
			        response);
		}
		
	}

	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect 0ed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}

%>

	<div id="page-wrap">
			<div id="inside">
				<div id="header_banner"></div>
						<div id="main-content-act">
        
								<div id="login">
									  <h1>Log in</h1>
									  <form id="form1" name="form1" method="post" action="">
										    <input type="username" placeholder="Username" name="username" style="font-size: 14px;" />
										    <input type="password" placeholder="Password" name="password" style="font-size: 14px;" />
										    <input type="submit" value="Log in" name ="submit" style="font-size: 14px;" />
									  </form>
								</div>
								<br/>
						</div>
					<div style="clear: both;"></div>
						<div id="footer"></div>
			</div>		
						<div style="clear: both;"></div>		
	</div>


<%		String x = request.getParameter("submit");
		System.out.println("X : "+x);////////////////try/////////////////
	    if("Log in".equals(x)) {
		   	String username = request.getParameter("username");
		   	String password = request.getParameter("password");
		   
		   
		   	System.out.println("username : "+username);////////////////try/////////////////
		   	System.out.println("password : "+password);////////////////try/////////////////		  
		   
			
		   	// check special character
		   	Pattern regex = Pattern.compile("[$&+,:;=?@#^*)(|!%]");
		   	Matcher matcherUser = regex.matcher(username);
		   	Matcher matcherPassword = regex.matcher(password);
		   	
		   	if (matcherUser.find() || matcherPassword.find()){
%>
				<script language="javascript"> alert("ชื่อผู้ใช้หรือรหัสผ่านที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง");	</script>
<%		   	}
		   	else {
		   		//////////QUERY SALT FROM DB/////////////
				List<Account> account = new ArrayList<Account>();
				System.out.println("STARTARTARTARTARTARTART");
				try {			   
					ResultSet rs = connect.createStatement().executeQuery("SELECT A.start_date, A.end_date, U.status, U.salt " 
							+ " FROM user U, account A "
							+ " WHERE U.username=A.username AND U.username='"+ username+"'");
					
					while(rs.next()) {
						Account acc = new Account();
						
						acc.setSalt(rs.getString("U.salt"));
						System.out.println("getSalt: "+acc.getSalt());
						account.add(acc);
					}
					
				} catch (SQLException e) {
					e.printStackTrace();
				}		
				
			   /////////////////////////////////////////////////// IF ADMIN //////////////////////////////////////////////////////////////////	
				String adminSalt = null;
			   	if(username.equals("admin")){
			   		System.out.println("admin");////////////////try/////////////////
			   	//Query for Admin's Salt			   
						ResultSet rs_user= connect.createStatement().executeQuery("SELECT `username`, `salt` "
								+ " FROM user"
								+ " WHERE username='"+ username+"'");
			   			
			   			if(rs_user.next()){
							adminSalt = rs_user.getString("salt");
							System.out.println("adminSalt: "+adminSalt);////////////////try/////////////////
			   			}
			   		
			   	 	// query password
			   	 	/* encrypt password */
				   	String Salt = adminSalt;
				   	System.out.println("Salt: "+Salt);
				   	String passwordSalt = password+Salt;
					String passwordEncrypt = PasswordHandler.encryptPassword(passwordSalt);
					System.out.println("passwordEncrypt: "+passwordEncrypt);
			   				
					try {
						ResultSet rs = connect.createStatement().executeQuery("SELECT `username`, `salt` " 
									+ " FROM user "
									+ " WHERE username='admin' AND password='" + passwordEncrypt + "'");
	
						rs.last();
						
						System.out.println("row: "+rs.getRow());////////////////try/////////////////
						if(rs.getRow() == 1) {
							// create session
							session.setAttribute("sUser", username);
							session.setMaxInactiveInterval(3360);
							
							/* Log file */
							String log = "admin login";
							Log.writeAdminFile(log);

	%>
							<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 
	<%			
						}
						else {
	%>
							<script language="javascript"> alert("รหัสผ่านที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง");	</script>
	<%
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}
				} 
		
			   	else {
			   		if(account.size() > 0) {
				   		/* encrypt password */
					   	String Salt = account.get(0).getSalt();
					   	System.out.println("Salt: "+Salt);
					   	String passwordSalt = password+Salt;
						String passwordEncrypt = PasswordHandler.encryptPassword(passwordSalt);
						System.out.println("passwordEncrypt: "+passwordEncrypt);
						
				   		// query username
						try {
							ResultSet rs = connect.createStatement().executeQuery("SELECT A.start_date, A.end_date, U.status " 
										+ " FROM user U, account A "
										+ " WHERE U.username=A.username AND U.username='"+ username +"' AND U.password='" + passwordEncrypt + "'");
							
							rs.last();
							if(rs.getRow() == 1) {
								// check status 						
								int status = rs.getInt("status");
								
								System.out.println("status : "+status);/////////////////////try/////////////////////
	
								if(status == 1) {
									// check start date & end date	
									SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.US);
									String start = rs.getString("start_date");
									String end = rs.getString("end_date");
									
									Calendar calendar = Calendar.getInstance();
									String current = sdf.format(calendar.getTime());
									
									Date startDate = sdf.parse(start);
									Date currentDate = sdf.parse(current);
									Date endDate = null;
									
									if(end != null) {
										endDate= sdf.parse(end);
									
										System.out.println("endDate : "+endDate);/////////////////////try/////////////////////							
									}
									
									System.out.println("startDate : "+startDate);/////////////////////try/////////////////////
									System.out.println("currentDate : "+currentDate);/////////////////////try/////////////////////
									
									// no end date & start after current
									if(end == null && !currentDate.after(startDate)) {
										System.out.println("NOT ACTIVE : 1 ************************");/////////////////////try/////////////////////
					%>
										<script language="javascript"> alert("บัญชีผู้ใช้นี้ยังไม่ถึงวันใช้งานค่ะ");	</script>
					<%
									}
									// have end date & start after current
									else if(end != null && !currentDate.after(startDate)) {
										System.out.println("NOT ACTIVE : 2 ************************");/////////////////////try/////////////////////
					%>
											<script language="javascript"> alert("บัญชีผู้ใช้นี้ยังไม่ถึงวันใช้งานค่ะ");	</script>
					<%		
									}
									// have end date & start before current
									else if(end != null && currentDate.after(startDate) && !currentDate.before(endDate)) {
										System.out.println("NOT ACTIVE : 3 ************************");/////////////////////try/////////////////////
					%>
											<script language="javascript"> alert("บัญชีผู้ใช้นี้เลยกำหนดวันใช้งานค่ะ");	</script>
					<%		
									}
									else {
										System.out.println("ACTIVE ************************");/////////////////////try/////////////////////
											
										// create session
										session.setAttribute("sUser", username);
										session.setMaxInactiveInterval(3360);
												
										String name = "";
										String surname = "";
										int num_system = 0;
										
										// check permisson
										try {
											ResultSet rsPermisson = connect.createStatement().executeQuery("SELECT F.name_th, R.permission, S.system_name, D.department_id, " 
													+ " F.surname_th, R.role_name "
													+ " FROM people P, account AC, user U, authorization AU, role R, system S, full_name F, workgroup W, department D "
													+ " WHERE F.full_name_id=P.full_name_id AND P.index=AC.index AND AC.username=U.username AND U.username=AU.username "
													+ " AND AU.role_id=R.role_id AND U.workgroup_id=W.workgroup_id AND W.department_id=D.department_id "
													+ " AND R.system_id=S.system_id AND U.username='" + username + "'");
											
											boolean checkStudent = true;
											boolean checkCurriculum = true;
											boolean checkEnroll = true;
											
											while(rsPermisson.next()) {
												
												String systemName = rsPermisson.getString("system_name");
				
												if("student".equals(systemName)) {
													session.setAttribute("student_system", "true");
													
													checkStudent = false;
													
													num_system++;
												}
												else if("curriculum".equals(systemName)) {
													session.setAttribute("curriculum_system", "true");
													
													checkCurriculum = false;
													
													num_system++;
												}
												else if("enrollment".equals(systemName)) {
													session.setAttribute("enrollment_system", "true");
													
													checkEnroll = false;
													
													num_system++;
												}
												
												// set parameter to session
												session.setAttribute("name", rsPermisson.getString("name_th"));
												session.setAttribute("surname", rsPermisson.getString("surname_th"));
												session.setAttribute("department_id", rsPermisson.getString("department_id"));
												session.setAttribute(systemName+"_role", rsPermisson.getString("role_name"));
												
												
												name = rsPermisson.getString("name_th");
												surname = rsPermisson.getString("surname_th");
												
												// set permission to session
												String numberPermission = rsPermisson.getString("permission");
												char[] permission = numberPermission.toCharArray();
												
												System.out.println("numberPermission : "+numberPermission);/////////////try///////////////
												System.out.println("permission[0] : "+permission[0]);/////////////try///////////////
												System.out.println("permission[1] : "+permission[1]);/////////////try///////////////
												System.out.println("permission[2] : "+permission[2]);/////////////try///////////////
												System.out.println("permission[3] : "+permission[3]);/////////////try///////////////
												
												// check create data
												if(permission[0] == '1') {
													session.setAttribute(systemName+"_create", "true");
												}
												else {
													session.setAttribute(systemName+"_create", "false");
												}
												
												// check update data
												if(permission[1] == '1') {
													session.setAttribute(systemName+"_update", "true");
												}
												else {
													session.setAttribute(systemName+"_update", "false");
												}
												
												// check read data
												if(permission[2] == '1') {
													session.setAttribute(systemName+"_read", "true");
												}
												else {
													session.setAttribute(systemName+"_read", "false");
												}
												
												// check delete data
												if(permission[3] == '1') {
													session.setAttribute(systemName+"_delete", "true");
												}
												else {
													session.setAttribute(systemName+"_delete", "false");
												}
												
											}
											
											if(checkStudent) {
												session.setAttribute("student_create", "false");
												session.setAttribute("student_update", "false");
												session.setAttribute("student_read", "false");
												session.setAttribute("student_delete", "false");
												
												session.setAttribute("student_role", "false");
												
												session.setAttribute("student_system", "false");
											}
											
											if(checkCurriculum) {
												session.setAttribute("curriculum_create", "false");
												session.setAttribute("curriculum_update", "false");
												session.setAttribute("curriculum_read", "false");
												session.setAttribute("curriculum_delete", "false");
												
												session.setAttribute("curriculum_role", "false");
												
												session.setAttribute("curriculum_system", "false");
											}
											
											if(checkEnroll) {
												session.setAttribute("enrollment_create", "false");
												session.setAttribute("enrollment_update", "false");
												session.setAttribute("enrollment_read", "false");
												session.setAttribute("enrollment_delete", "false");
												
												session.setAttribute("enrollment_role", "false");
												
												session.setAttribute("enrollment_system", "false");
											}
											
											// number of system
											session.setAttribute("num_system", num_system);
											
											/* Log file */
											String log = username+" "+name+" "+surname+" login";
											Log.writeUserFile(log);
											
				%>
											<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp">   
				<%							
										} catch (SQLException e) {
											e.printStackTrace();
										}	
									} // end check start&end date
								} // end if check status
								else {
			%>
									<script language="javascript"> alert("บัญชีผู้ใช้นี้ไม่สามารถเข้าใช้งานได้ กรุณาติดต่อ admin ค่ะ");	</script>
			<%							
								}
							} // end if check username&password
							
							else {
		%>
								<script language="javascript"> alert("บัญชีผู้ใช้หรือรหัสผ่านที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง");	</script>
		<%
							}
						} catch (SQLException e) {
							e.printStackTrace();
						}			
					} // end if check size account
					else {
		%>
						<script language="javascript"> alert("บัญชีผู้ใช้หรือรหัสผ่านที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง");	</script>
		<%				
					}
			   	} // end else check user
		   	}
			
		}
		
	    connect.close();
%>
</body>
</html>